/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.statistics.riskanddanger;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.domain.KpiStatistics;
import com.koron.common.mapper.KpiStatisticsMapper;
import com.koron.common.web.Util;
import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.report.bean.StatisticsBean;
import com.koron.report.management.StatisticsManagement;
import com.koron.report.mapper.statistics.FreeSnapNumberStatisticsMapper;
import com.koron.report.statistics.StatisticsService;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.risk.service.api.GridNodeService;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.service.api.DistrictService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 随手拍次数统计业务实现类，指标库编码为0109
 */
@Service("FreeSnapNumberStatisticsService")
public class FreeSnapNumberStatisticsServiceImpl  implements StatisticsService, InitializingBean {

    private final static  Logger logger= LoggerFactory.getLogger(FreeSnapNumberStatisticsServiceImpl.class);

    @Autowired
    private StatisticsManagement statisticsManagement;

    @Autowired
    private Util util;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private GridNodeService gridNodeService;

    @Autowired
    private DistrictService districtService;

    @Override
    public void afterPropertiesSet() throws Exception {
        Set<Object> handlers = statisticsManagement.getHandlers();
        handlers.add(this);
    }

    @Override
    public void statisticsMonth(int year, int month) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, month-1,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month,1,0,0,0);
            Date endTime=calendar.getTime();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            int dateType=1;
            //计算随手拍次数，所有统计层级
            countFreeSnapNumber(simpleDateFormat,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("随手拍次数按月统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsQuarter(int year, int quarter) {
        try{
            Calendar calendar=Calendar.getInstance();
            int month=0;
            switch (quarter){
                case 1:
                    break;
                case 2:
                    month=3;
                    break;
                case 3:
                    month=6;
                    break;
                case 4:
                    month=9;
                    break;
                default:
                    break;
            }
            calendar.set(year, month,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month+2,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=2;
            //计算随手拍次数，所有统计层级
            countFreeSnapNumber(null,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("随手拍次数按季度统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsYear(int year) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, 0,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year+1, 0,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=3;
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy");
            //计算随手拍次数，所有统计层级
            countFreeSnapNumber(simpleDateFormat,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("随手拍次数按年统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    public void countFreeSnapNumber(SimpleDateFormat format,Integer dateType, Date startTime, Date endTime){
        SessionFactory factory=null;
        String kpiTemplateCode="0109";
        try{
            factory=new SessionFactory();
            //先删除对应的指标的数据，某个日期类型下的所有统计层级
            String dataValue=getDateValue(dateType,startTime);
            factory.getMapper(KpiStatisticsMapper.class).delete(kpiTemplateCode,dataValue,null);
            //计算部门
            countFreeSnapNumberByDeptOrGroup(factory,format,dateType,2,startTime,endTime,kpiTemplateCode);
            //计算水司
            countFreeSnapNumberByCorp(factory,format,dateType,startTime,endTime,kpiTemplateCode);
            //计算片区
            countFreeSnapNumberByDitrict(factory,format,dateType,startTime,endTime,kpiTemplateCode);
            //计算集团
            countFreeSnapNumberByDeptOrGroup(factory,format,dateType,1,startTime,endTime,kpiTemplateCode);
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(dateType==2?getDateValue(dateType,startTime):format.format(startTime)+"计算指标库code为"+kpiTemplateCode+
                    "失败，失败原因为："+e.getMessage());
            logger.error(e.getMessage(),e);
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    /**
     * 设置kpi指标的通用数据值
     * @param template
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date 日期
     * @return
     */
    private KpiStatistics generateKpiStatistics(KPITemplate template, Integer type, Date date){
        KpiStatistics kpiStatistics=new KpiStatistics();
        kpiStatistics.setKpiId(template.getId());
        kpiStatistics.setKpiCode(template.getCode());
        kpiStatistics.setKpiName(template.getName());
        //判断如何设置日期，1代表是月份，2代表是季度，3代表是年
        kpiStatistics.setDateType(type);
        kpiStatistics.setDateValue(getDateValue(type,date));
        return  kpiStatistics;
    }

    /**
     *根据日期和日期类型，获取相应的日期字符串
     * 月份返回形如2020-02，季度返回2020-1，年返回2020
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date  日期
     * @return
     */
    private String getDateValue(Integer type,Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        switch (type){
            case 1:
                return ""+year+"-"+(month<10?"0"+month:month);
            case 2:
                return ""+year+"-"+(month/3+1);
            case 3:
                return year+"";
            default:
                return "";
        }
    }

    /**
     * 统计随手拍次数，统计层级为部门或者集团，通过参数statisticsType 区分
     * @param dateType 日期类型 1，月，2，季度，3 年
     * @param statisticsType 统计层级类型，1：集团，2 部门
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode  指标库code
    */
    public void countFreeSnapNumberByDeptOrGroup(SessionFactory factory, SimpleDateFormat format,Integer dateType, Integer statisticsType,
                                                 Date startTime, Date endTime,String kpiTemplateCode) throws Exception {
        //判断统计层级类型值是否合法
        if (statisticsType!=1&&statisticsType!=2){
            logger.error("统计随手拍次数失败，参数区分统计层级为部门或集团不合法，1集团，2部门");
            return;
        }
        FreeSnapNumberStatisticsMapper freeSnapNumberStatisticsMapper=factory.getMapper(FreeSnapNumberStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        //判断是统计集团还是统计部门
        if (statisticsType==1){
            //统计集团
            Integer total=freeSnapNumberStatisticsMapper.countFreeSnapNumberByDeptOrGroup(startTime,endTime,null);
            kpiStatisticsList=new ArrayList<>();
            //获取当前统计指标实体类
            KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
            KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
            kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
            kpiStatistics.setObjectName("粤海水资源");
            kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
            kpiStatistics.setStatisticalType(5);
            kpiStatistics.setAddTime(date);
            kpiStatisticsList.add(kpiStatistics);
        }else{
            //统计部门
            //先获取当前组织架构上所有的部门
            List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("c75d5edacbc042448dab01951208421b",1).getData();
            if (null==departmentTreeBeanList&&departmentTreeBeanList.size()<=0){
                return;
            }
            //获取当前标志为水司的部门（组织架构）
            List<CorpBean> corpBeanList=corpManagementService.corpBeanList();

            //  将当前获取的所有部门排除当前为水司，以及当前集团的的code 先排除集团
            List<DepartmentTreeBean> departmentTreeBeanList1=null;
            departmentTreeBeanList1=departmentTreeBeanList.stream().filter(d->d.getOrgCode().equals("c75d5edacbc042448dab01951208421b")).collect(Collectors.toList());
            //再排除水司
            List<String> corpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
            List<DepartmentTreeBean> result=null;
            result=departmentTreeBeanList1.stream().filter(d->!(corpCodeList.contains(d.getDepartmentCode()))).collect(Collectors.toList());
            //循环查询每个部门下有多少个整改隐患
            kpiStatisticsList=new ArrayList<>();
            for(DepartmentTreeBean departmentTreeBean:result){
                //查询该部门下所有子部门以及所有网格
                MessageBean<?> msg=gridNodeService.childList(departmentTreeBean.getDepartmentCode(),1);
                //存储部门和网格code
                List<String> codeList=new ArrayList<>();
                if (msg.getData()!=null) {
                    List<Map<String,String>> mapList= (List<Map<String, String>>) msg.getData();
                    codeList=mapList.stream().map(m->m.get("code")).collect(Collectors.toList());
                }else{
                    codeList.add(departmentTreeBean.getDepartmentCode());
                }
                Integer total=0;
                if (codeList!=null&&codeList.size()>0){
                    total=freeSnapNumberStatisticsMapper.countFreeSnapNumberByDeptOrGroup(startTime,endTime,codeList);
                }
                if (total>0){
                    //获取当前统计指标实体类
                    KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                    kpiStatistics.setObjectId(departmentTreeBean.getDepartmentCode());
                    kpiStatistics.setObjectName(departmentTreeBean.getName());
                    kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                    kpiStatistics.setStatisticalType(2);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if (null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为"+(statisticsType==1?"集团":"部门")+"失败");
            }
        }
    }

    /**
     * 统计随手拍次数，统计层级为水司
     * @param dateType 日期类型 1，月，2，季度，3 年
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode  指标库code
     */
    public void countFreeSnapNumberByCorp(SessionFactory factory, SimpleDateFormat format,Integer dateType, Date startTime, Date endTime,String kpiTemplateCode) throws Exception {
        FreeSnapNumberStatisticsMapper freeSnapNumberStatisticsMapper=factory.getMapper(FreeSnapNumberStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        //获取指标库模板
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode(kpiTemplateCode);
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        List<StatisticsBean> statisticsBeanList=freeSnapNumberStatisticsMapper.countFreeSnapNumberByCorp(startTime,endTime);
        if (statisticsBeanList!=null&&statisticsBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            for(StatisticsBean statisticsBean:statisticsBeanList){
                //由于数据问题，在统计时没有办法取到水司的名称，在此之前需要根据水司code获取水司的名称
                CorpBean corpBean=factory.getMapper(CorpManagementMapper.class).get(statisticsBean.getCode());
                //水司不存在，结束本次循环
                if (null==corpBean){
                    continue;
                }
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                kpiStatistics.setKpiValue(Float.parseFloat(statisticsBean.getValue()));
                kpiStatistics.setObjectId(statisticsBean.getCode());
                kpiStatistics.setObjectName(corpBean.getCorpName());
                kpiStatistics.setStatisticalType(3);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为水司失败");
            }
        }
    }

    public void countFreeSnapNumberByDitrict(SessionFactory factory, SimpleDateFormat format,Integer dateType, Date startTime, Date endTime,String kpiTemplateCode) throws Exception {
        FreeSnapNumberStatisticsMapper freeSnapNumberStatisticsMapper=factory.getMapper(FreeSnapNumberStatisticsMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        //获取指标库模板
        KPITemplate kpiTemplate=templateMapper.queryTemplateByCode(kpiTemplateCode);
        List<KpiStatistics> kpiStatisticsList=null;
        Date date=new Date();
        List<District> districtList=factory.getMapper(DistrictMapper.class).queryAllDistrict(null,null);
        if(null!=districtList&&districtList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            for(District district:districtList){
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> corpCodeList=relationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                if (corpCodeList!=null&&corpCodeList.size()>0){
                    Integer total=freeSnapNumberStatisticsMapper.countFreeSnapNumberByDistrict(startTime,endTime,corpCodeList);
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,dateType,startTime);
                    kpiStatistics.setObjectId(district.getCode());
                    kpiStatistics.setObjectName(district.getName());
                    kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                    kpiStatistics.setStatisticalType(4);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为片区失败");
            }
        }

    }
}
